package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"house123/C/srv/model/es"
	"house123/C/srv/model/mysql"
	"log"
	"strconv"
	"sync"

	"house123/C/srv/house"
	"house123/C/srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SyncEsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSyncEsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SyncEsLogic {
	return &SyncEsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SyncEsLogic) SyncEs(in *house.SyncEsRequest) (*house.SyncEsResponse, error) {
	// todo: add your logic here and delete this line
	var (
		goods []*mysql.Goods
		wg    sync.WaitGroup
	)
	mysql.DB.Find(&goods)
	for _, title := range goods {
		wg.Add(1)

		go func(good *mysql.Goods) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(good)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "goods",
				DocumentID: strconv.Itoa(int(good.ID)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), es.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(title)
	}
	wg.Wait()
	return &house.SyncEsResponse{}, nil
}
